﻿using BootstrapBlazor.Components;
using CodeMan.Application.Contracts.ClassGens; 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeMan.Data.DataServiceBaseExts
{
    public static class FooDemoExts
    {
        public static bool Query<TModel>(this FooDemo model, IEnumerable<TModel> items)
            where TModel : class, new()
        {
            if (!string.IsNullOrEmpty(model.Name)) items = items.Cast<FooDemo>().Where(item => item.Name?.Contains(model.Name, StringComparison.OrdinalIgnoreCase) ?? false).Cast<TModel>();
            if (!string.IsNullOrEmpty(model.Address)) items = items.Cast<FooDemo>().Where(item => item.Address?.Contains(model.Address, StringComparison.OrdinalIgnoreCase) ?? false).Cast<TModel>();
            var isSearched = !string.IsNullOrEmpty(model.Name) || !string.IsNullOrEmpty(model.Address);

            return isSearched;
        }

        public static bool Save<TModel>(this FooDemo foo, List<TModel> Items)
            where TModel : class, new()
        {
            var item = Items?.FirstOrDefault(item =>
            {
                var f = item as FooDemo;
                return f.Id == foo.Id;
            });
            if (item == null)
            {
                var id = Items!.Count() + 1;
                while (Items.FirstOrDefault(item => (item as FooDemo)!.Id == id) != null)
                {
                    id++;
                }
                item = new FooDemo()
                {
                    Id = id,
                    Name = foo.Name,
                    Address = foo.Address,
                    Complete = foo.Complete,
                    Count = foo.Count,
                    DateTime = foo.DateTime,
                    Education = foo.Education,
                    Hobby = foo.Hobby
                } as TModel;
                Items?.Add(item!);
            }
            else
            {
                var f = item as FooDemo;
                f.Name = foo.Name;
                f.Address = foo.Address;
                f.Complete = foo.Complete;
                f.Count = foo.Count;
                f.DateTime = foo.DateTime;
                f.Education = foo.Education;
                f.Hobby = foo.Hobby;
            }
            return true;
        }
    }
}
